using Microsoft.EntityFrameworkCore;
using System;
using System.IO;
using FileManager.Models;

namespace FileManager.Models
{
    public class AppDbContext : DbContext
    {
        public DbSet<FileItem> Files { get; set; }
        public DbSet<ChatObject> ChatObjects { get; set; }
        public DbSet<Tag> Tags { get; set; }
        public DbSet<FileChatRelation> FileChatRelations { get; set; }
        public DbSet<FileTagRelation> FileTagRelations { get; set; }
        
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // 使用相对路径而不是硬编码的绝对路径
            string dbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FileManager.db3");
                
            // 确保目录存在
            Directory.CreateDirectory(Path.GetDirectoryName(dbPath));
            
            optionsBuilder.UseSqlite($"Data Source={dbPath}");
        }
        
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // 配置唯一索引
            modelBuilder.Entity<FileItem>()
                .HasIndex(f => f.FilePath)
                .IsUnique();
                
            modelBuilder.Entity<ChatObject>()
                .HasIndex(c => c.WeChatId)
                .IsUnique();
                
            modelBuilder.Entity<Tag>()
                .HasIndex(t => t.Name)
                .IsUnique();
                
            // 配置复合唯一索引
            modelBuilder.Entity<FileChatRelation>()
                .HasIndex(r => new { r.FileId, r.ChatObjectId })
                .IsUnique();
                
            modelBuilder.Entity<FileTagRelation>()
                .HasIndex(ft => new { ft.FileId, ft.TagId })
                .IsUnique();
                
            // 配置级联删除
            modelBuilder.Entity<FileChatRelation>()
                .HasOne(r => r.File)
                .WithMany(f => f.ChatRelations)
                .HasForeignKey(r => r.FileId)
                .OnDelete(DeleteBehavior.Cascade);

            modelBuilder.Entity<FileChatRelation>()
                .HasOne(r => r.ChatObject)
                .WithMany(c => c.FileChatRelations)
                .HasForeignKey(r => r.ChatObjectId)
                .OnDelete(DeleteBehavior.Cascade);
                
            modelBuilder.Entity<FileTagRelation>()
                .HasOne(ft => ft.File)
                .WithMany(f => f.FileTagRelations)
                .HasForeignKey(ft => ft.FileId)
                .OnDelete(DeleteBehavior.Cascade);
                
            modelBuilder.Entity<FileTagRelation>()
                .HasOne(ft => ft.Tag)
                .WithMany(t => t.FileTagRelations)
                .HasForeignKey(ft => ft.TagId)
                .OnDelete(DeleteBehavior.Cascade);
        }
    }
}